//
//  LoginViewController.m
//  GuMoonNews
//
//  Created by 胡发冬 on 16/8/1.
//  Copyright © 2016年 胡发冬. All rights reserved.
//
//

#define screenWidth [[UIScreen mainScreen]bounds].size.width
#define screenHeight [[UIScreen mainScreen]bounds].size.height


#import "LoginViewController.h"

#import "sys/utsname.h"

#import "Soap.h"
#import "XMLReader.h"



@interface LoginViewController ()
{
    UIViewController *mainViewController;


    UIImageView *backView;
    UIImageView *urlView;
    
    NSString *verification;
    
    int seconds;
    
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //将storyBoard实例化，“Main”为StoryBoard的名称
    UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //将控制器实例化
    mainViewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"MainViewController"];
    
    backView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    
    [backView setImage:[UIImage imageNamed:@"back.png"]];
    
    urlView = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth-190, screenHeight-145, 180, 45)];
    
    [urlView setImage:[UIImage imageNamed:@"gumoonurl.PNG"]];
    
    seconds = 10;
    
    
    [_mobilenumber  setValue:[UIColor colorWithRed:0.71 green:0.81 blue:0.71 alpha:0.6] forKeyPath:@"_placeholderLabel.textColor"];
    
    //[_mobilenumber setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    
    //[_verificationcode  setValue:[UIColor colorWithRed:0.71 green:0.81 blue:0.71 alpha:0.6] forKeyPath:@"_placeholderLabel.textColor"];
    
    //[_verificationcode setValue:[UIFont boldSystemFontOfSize:20] forKeyPath:@"_placeholderLabel.font"];
    

    NSMutableParagraphStyle *style = [_mobilenumber.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    
    style.minimumLineHeight =( _mobilenumber.font.lineHeight - [UIFont systemFontOfSize:18.0].lineHeight) / 2.0;
    
    
    NSMutableParagraphStyle *style1 = [_verificationcode.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    
    style.minimumLineHeight =( _verificationcode.font.lineHeight - [UIFont systemFontOfSize:18.0].lineHeight) / 2.0;

    
    
    _mobilenumber.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号"
                                           
                                                                          attributes:@{
                                                                                       
                                                                                       NSForegroundColorAttributeName: [UIColor colorWithRed:0.71 green:0.81 blue:0.71 alpha:0.6],
                                                                                       
                                                                                       NSFontAttributeName : [UIFont systemFontOfSize:18.0],
                                                                                       
                                                                                       NSParagraphStyleAttributeName : style
                                                                                       
                                                                                       }
                                           
                                           ];
    _verificationcode.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码"
                                               
                                                                              attributes:@{
                                                                                           
                                                                                           NSForegroundColorAttributeName: [UIColor colorWithRed:0.71 green:0.81 blue:0.71 alpha:0.6],
                                                                                           
                                                                                           NSFontAttributeName : [UIFont systemFontOfSize:18.0],
                                                                                           
                                                                                           NSParagraphStyleAttributeName : style1
                                                                                           
                                                                                           }
                                               
                                               ];


    _mobilenumber.delegate=self;
    _verificationcode.delegate=self;
    
    verification=@"verification";
    

    [self performSelector:@selector(addLogBtn) withObject:nil afterDelay:0.5f];
    
    //[self addLogBtn];
    
    
}




-(void)timerFireMethod:(NSTimer *)theTimer {
    if (seconds == 1) {
        [theTimer invalidate];
        seconds = 10;
        [_getverificationcodeBtn setTitle:@"点击获取验证码" forState: UIControlStateNormal];
        [_getverificationcodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [_getverificationcodeBtn setEnabled:YES];
    }else{
        seconds--;
        NSString *title = [NSString stringWithFormat:@"%d秒后重新获取",seconds];
//        [_getverificationcodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//        [_getverificationcodeBtn setEnabled:NO];
        [_getverificationcodeBtn setTitle:title forState:UIControlStateNormal];

    }
}


-(void)addLogBtn{
    
    [self.view addSubview:urlView];
    [self.view addSubview:backView];
    
    [self.view sendSubviewToBack:backView];
    
    
    UIButton *LogBtn = [[UIButton alloc]init];
                        //Frame:CGRectMake(screenWidth - 186.0,screenHeight - 92.0,180.0,50.0)];
    
    [LogBtn setBackgroundImage:[UIImage imageNamed:@"buttonlog.png"] forState:UIControlStateNormal];
    
    [LogBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    if (screenWidth<=320) {
        [LogBtn setFrame:CGRectMake(screenWidth - 186.0,screenHeight - 92.0,180.0,50.0)];
        [UIView animateWithDuration:0.5
                         animations:^{
                             [LogBtn setFrame:CGRectMake(screenWidth - 190.0,screenHeight - 92.0,180.0,50.0)];
                         }
                         completion:^(BOOL finished) {
                         }];
    }else{
        [LogBtn setFrame:CGRectMake(screenWidth - 190.0,screenHeight - 92.0,180.0,50.0)];
    }

    
    
    
    [self.view addSubview:LogBtn];
    
}


- (IBAction)GetVerificationCode:(UIButton *)sender {

    //NSLog(@"1");
    
    if (_mobilenumber.text.length == 11) {
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        [timer awakeFromNib];
        [_getverificationcodeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_getverificationcodeBtn setEnabled:NO];
        
        
        int ran = arc4random()%10000;
        NSString *ran_str = [NSString stringWithFormat:@"%04d",ran];
        NSLog(@"%@",ran_str);
        
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if ([ran_str isEqualToString:[userDefaults objectForKey:@"random_str"]]) {
            
        }
        
        [userDefaults setObject:ran_str forKey:@"random_str"];
        [userDefaults synchronize];

        
        
        NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"18800888888",@"tel",nil];
        NSString *methodName=@"SMS";
        SoapUtility *soaputility=[[SoapUtility alloc] initFromFile:@"SMSWebService.asmx"];
        NSString *postData=[soaputility BuildSoapwithMethodName:methodName withParas:dic];
        SoapService *soaprequest=[[SoapService alloc] init];
        soaprequest.PostUrl=@"http://192.168.0.154:869/SMSWebService.asmx";
        soaprequest.SoapAction=[soaputility GetSoapActionByMethodName:methodName SoapType:SOAP];
        //同步方法
        ResponseData *result= [soaprequest PostSync:postData];
        NSString *res = [NSString stringWithFormat:@"%@",[XMLReader dictionaryForXMLString:result.Content error:nil]];
        NSLog(@"%@",res);
        
        

        
        
        
        
        
        
        
        
        //手机别名： 用户定义的名称
        NSString* userPhoneName = [[UIDevice currentDevice] name];
        NSLog(@"手机别名: %@", userPhoneName);
        //手机系统版本
        NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
        NSLog(@"手机系统版本: %@", phoneVersion);
        //手机型号
        struct utsname systemInfo;
        uname(&systemInfo);
        NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
        NSLog(@"手机型号：%@",deviceString);
        
        
        
        
        
        
        
        
        
        NSLog(@"%@",verification);
        NSLog(@"%@",_mobilenumber.text);
        
        
        
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"手机号输入有误" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
        [alertController addAction:okAction];
        [super presentViewController:alertController animated:YES completion:nil];
    }
    
    
    
    
    
    
    
    
    
    
    

    
}

- (IBAction)dismissKeyboard:(UIButton *)sender {
    
    [self missKeyboard];
    
    
}

-(void)missKeyboard{
    NSLog(@"KeyboardMiss");
    
    for (UITextField *tf in self.view.subviews) {
        [tf resignFirstResponder];
    }
    
    [self ResetFrame];
}

- (void)login{
    
    if (_verificationcode.text.length==4) {
        NSLog(@"%@",verification);
        NSLog(@"%@",_verificationcode.text);

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        [userDefaults setObject:@"1" forKey:@"loginStatus"];
        
        [userDefaults synchronize];
        
        NSLog(@"loginStatus=%@",[userDefaults objectForKey:@"loginStatus"]);
        
        [mainViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        
        //[self dismissViewControllerAnimated:YES completion:nil];
        
        //[self presentViewController:mainViewController animated:YES completion:nil];
        
        [self.navigationController pushViewController: mainViewController animated:true];
        
        //[self dismissViewControllerAnimated:YES completion:nil];
        
        
    }else{

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"验证码输入有误" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {}];
        [alertController addAction:okAction];
        [super presentViewController:alertController animated:YES completion:nil];
        
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setObject:@"1" forKey:@"loginStatus"];
    
    [userDefaults synchronize];
    
    NSLog(@"loginStatus=%@",[userDefaults objectForKey:@"loginStatus"]);
    
    [mainViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
    [self presentViewController:mainViewController animated:YES completion:nil];
    
}

- (IBAction)teltextBegin:(UITextField *)sender {
    
    [self ChangeFrameUp:120.0];
    
    
    
}

- (IBAction)teltextChanged:(UITextField *)sender {

    if (sender.text.length >11) {
        sender.text =  [sender.text substringToIndex:11];
    }
    
}


- (IBAction)vctextBegin:(UITextField *)sender {
    [self ChangeFrameUp:120.0];

}


- (IBAction)vctextChanged:(UITextField *)sender {

    if (sender.text.length >4) {
        sender.text =  [sender.text substringToIndex:4];
    }
    
    
}









-(void)ChangeFrameUp:(float)Up{
    
    CGRect rect = CGRectMake(0, -Up,screenWidth,screenHeight);
    
    [UIView animateWithDuration:0.2
                          animations:^{
                            self.view.frame = rect;
                          }
                          completion:^(BOOL finished) {
                          }];
}

-(void)ResetFrame{
    
    CGRect rect = CGRectMake(0, 0,screenWidth,screenHeight);
    [UIView animateWithDuration:0.2
                     animations:^{
                         self.view.frame = rect;
                     }
                     completion:^(BOOL finished) {
                     }];
    
}
#pragma mark - 点击键盘return键时
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //我选择在这个地方回收键盘
    //当文本框处于编辑状态时就是第一响应者，想回收键盘，就要取消第一响应者
    [textField resignFirstResponder];
    [self ResetFrame];
    
    return NO;
}




@end
